package com.che.software.testato.domain.dao.jdbc.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.che.software.testato.domain.dao.IPrioritizationDAO;
import com.che.software.testato.domain.dao.jdbc.adao.AbstractDAO;
import com.che.software.testato.domain.dao.jdbc.exception.PrioritizationCreationDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.PrioritizationSearchDAOException;
import com.che.software.testato.domain.entity.Prioritization;
import com.che.software.testato.domain.entity.search.PrioritizationSearch;

/**
 * JDBC implementation of the DAO interface dedicated to the prioritizations
 * management.
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @copyright Che Software.
 * @license GNU General Public License.
 * @see AbstractDAO, IPrioritizationDAO.
 * @since July, 2011.
 * 
 *        This file is part of Testato.
 * 
 *        Testato is free software: you can redistribute it and/or modify it
 *        under the terms of the GNU General Public License as published by the
 *        Free Software Foundation, either version 3 of the License, or (at your
 *        option) any later version.
 * 
 *        Testato is distributed in the hope that it will be useful, but WITHOUT
 *        ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *        FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *        for more details.
 * 
 *        You should have received a copy of the GNU General Public License
 *        along with Testato. If not, see <http://www.gnu.org/licenses/>.
 * 
 *        Testato's logo is a creation of Arrioch
 *        (http://arrioch.deviantart.com/) and it's distributed under the terms
 *        of the Creative Commons License.
 */
@Repository("prioritizationDAO")
public class PrioritizationDAO extends AbstractDAO implements IPrioritizationDAO {

	/**
	 * Constants.
	 */
	private static final Logger LOGGER = Logger.getLogger(PrioritizationDAO.class);

	/**
	 * Creates the prioritization related to the given hierarchy.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param hierarchyId the given hierarchy id.
	 * @since July, 2011.
	 * @throws PrioritizationCreationDAOException if an error occurs during the
	 *         creation.
	 */
	@Override
	public void createHierarchyPrioritization(int hierarchyId) throws PrioritizationCreationDAOException {
		LOGGER.debug("createHierarchyPrioritization(" + hierarchyId + ").");
		Connection connection = null;
		try {
			connection = getDataSource().getConnection();
			connection.setAutoCommit(false);
			getQueryRunner().update(connection, "INSERT INTO prioritization(prioritization_id) VALUES(nextval('prioritization_seq')) ");
			Integer createdPrioritization = (Integer) getQueryRunner().query(connection, "SELECT MAX(prioritization_id)::int AS prioritizationId FROM prioritization ", new ScalarHandler("prioritizationId"));
			getQueryRunner().update(connection, "INSERT INTO hierarchy_prioritization(hierarchy_id, prioritization_id) VALUES(?,?) ", new Object[] { hierarchyId, createdPrioritization });
			connection.commit();
		} catch (SQLException e) {
			try {
				connection.rollback();
			} catch (SQLException e1) {
				throw new PrioritizationCreationDAOException(e);
			}
			throw new PrioritizationCreationDAOException(e);
		} finally {
			if (null != connection) {
				DbUtils.closeQuietly(connection);
			}
		}
	}

	/**
	 * Prioritization search from a bean of criterions.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param searchBean the criterions to use for the search.
	 * @return the resulting object list.
	 * @since July, 2011.
	 * @throws PrioritizationSearchDAOException if an error occurs during the
	 *         search.
	 */
	@Override
	public List<Prioritization> searchPrioritization(PrioritizationSearch searchBean) throws PrioritizationSearchDAOException {
		LOGGER.debug("searchPrioritization().");
		Connection connection = null;
		try {
			connection = getDataSource().getConnection();
			List<Object> params = new ArrayList<Object>();
			return getQueryRunner().query(connection, getPrioritizationSearchQueryFromCriterion(searchBean, params), new BeanListHandler<Prioritization>(Prioritization.class), params.toArray());
		} catch (SQLException e) {
			throw new PrioritizationSearchDAOException(e);
		} finally {
			if (null != connection) {
				DbUtils.closeQuietly(connection);
			}
		}
	}

	/**
	 * Recovery of the prioritization search query from criterion.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param searchBean the object containing the criterions.
	 * @param params the parameters list corresponding to the built query.
	 * @return the built query.
	 * @since July, 2011.
	 */
	private String getPrioritizationSearchQueryFromCriterion(PrioritizationSearch searchBean, List<Object> params) {
		LOGGER.debug("getPrioritizationSearchQueryFromCriterion().");
		setWhereClauseEnabled(false);
		StringBuilder sBuilder = new StringBuilder("SELECT prioritization_id AS prioritizationId, hierarchy_id AS hierarchyId FROM prioritization JOIN hierarchy_prioritization USING(prioritization_id) ");
		if (null != searchBean && null != searchBean.getHierarchyId() && 0 != searchBean.getHierarchyId()) {
			sBuilder.append(getWhereClauseBegin());
			sBuilder.append("hierarchy_id = ? ");
			params.add(searchBean.getHierarchyId());
		}
		return sBuilder.toString();
	}
}